<!--
 * @Description: 监测点信息
 * @Author: Ronda
 * @Date: 2022-02-16 09:30:08
 * @LastEditors: Ronda
 * @LastEditTime: 2022-05-23 15:22:35
-->
<template>
  <div>
    <el-row>
      <el-col :span="4">
        <div class="tree">
          <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
          <el-tree
            class="filter-tree"
            :data="empData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
            ref="tree"
          ></el-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <div v-if="currentDevice.id" class="device-detail">
          <!-- 设备信息卡片 -->
          <el-card class="box-card mb-6" shadow="hover">
            <template #header>
              <div class="clearfix">
                <span class="text-lg font-semibold">设备详细信息</span>
                <el-button 
                  style="float: right; padding: 3px 0" 
                  type="text" 
                  @click="refreshDeviceInfo"
                  :loading="loading"
                >
                  <i class="el-icon-refresh"></i> 刷新
                </el-button>
              </div>
            </template>
            <div class="p-4 grid grid-cols-2 gap-4">
              <div class="flex items-center">
                <span class="text-gray-500 w-24">设备名称：</span>
                <span class="font-medium">{{ currentDevice.name || '-' }}</span>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">设备编号：</span>
                <span class="font-medium">{{ currentDevice.serial_number || '-' }}</span>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">绑定状态：</span>
                <el-tag :type="currentDevice.bind_status === 1 ? 'success' : 'danger'">
                  {{ currentDevice.bind_status === 1 ? '已绑定' : '未绑定' }}
                </el-tag>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">在线状态：</span>
                <el-tag :type="currentDevice.online_status === 1 ? 'success' : 'danger'">
                  {{ currentDevice.online_status === 1 ? '在线' : '离线' }}
                </el-tag>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">经度：</span>
                <span class="font-medium">{{ currentDevice.longitude || '-' }}</span>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">纬度：</span>
                <span class="font-medium">{{ currentDevice.latitude || '-' }}</span>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">安装时间：</span>
                <span class="font-medium">{{ formatTime(currentDevice.insert_time) || '-' }}</span>
              </div>
      
            </div>
          </el-card>

          <!-- 工程信息卡片 -->
          <el-card class="box-card mb-6" shadow="hover">
            <template #header>
              <div class="clearfix">
                <span class="text-lg font-semibold">关联工程信息</span>
              </div>
            </template>
            <div class="p-4 grid grid-cols-2 gap-4">
              <div class="flex items-center">
                <span class="text-gray-500 w-24">工程编号：</span>
                <span class="font-medium">{{ engineerInfo.serial_number || '-' }}</span>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">工程名称：</span>
                <span class="font-medium">{{ engineerInfo.name || '-' }}</span>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">工程类型：</span>
                <span class="font-medium">{{ engineerInfo.type || '-' }}</span>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">工程状态：</span>
                <el-tag :type="getStatusType(engineerInfo.status)" effect="dark">
                  {{ engineerInfo.status || '-' }}
                </el-tag>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">负责人：</span>
                <span class="font-medium">{{ engineerInfo.charge_id ? `工号：${engineerInfo.charge_id}` : '-' }}</span>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">创建时间：</span>
                <span class="font-medium">{{ formatTime(engineerInfo.create_time) }}</span>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">开始时间：</span>
                <span class="font-medium">{{ formatTime(engineerInfo.begin_time) }}</span>
              </div>
              <div class="flex items-center">
                <span class="text-gray-500 w-24">结束时间：</span>
                <span class="font-medium">{{ formatTime(engineerInfo.end_time) }}</span>
              </div>
              <div class="flex items-center col-span-2">
                <span class="text-gray-500 w-24">详细地址：</span>
                <span class="font-medium">{{ formatAddress(engineerInfo.address) }}</span>
              </div>
            </div>
          </el-card>

          <!-- 地图卡片 -->
          <el-card class="box-card" shadow="hover" v-if="showMap">
            <template #header>
              <div class="clearfix">
                <span class="text-lg font-semibold">设备位置地图</span>
                <el-button 
                  style="float: right; padding: 3px 0" 
                  type="text" 
                  @click="toggleMap"
                >
                  {{ showMap ? '隐藏地图' : '显示地图' }}
                </el-button>
              </div>
            </template>
            <div class="map-container">
              <div class="map-placeholder">
                地图组件区域（经纬度：{{ currentDevice.longitude || '-' }}, {{ currentDevice.latitude || '-' }}）
              </div>
            </div>
          </el-card>
        </div>
        <div v-else class="empty-tip">
          <el-empty 
            description="请从左侧选择设备查看详细信息"
            image="el-icon-info"
            image-style="width: 100px; height: 100px; color: #909399"
          >
            <template #content>
              <el-button type="primary" disabled>查看设备详情</el-button>
            </template>
          </el-empty>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { get } from '@/utils/request'

export default {
  data() {
    return {
      filterText: '',
      empData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      currentDevice: {},
      engineerInfo: {},
      showMap: true,
      loading: false
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    // 节点点击处理
    async handleNodeClick(nodeData) {
      if (!nodeData.children) {
        this.loading = true
        try {
          // 获取设备详情（已包含完整工程信息）
          const deviceRes = await get('/device/findDeviceDetail', { id: nodeData.id })
          this.currentDevice = deviceRes.data
          
          // 从设备详情中提取工程信息
          this.engineerInfo = this.currentDevice.engineer || {}
          
          this.$message.success('设备信息加载成功')
        } catch (error) {
          this.$message.error('获取设备信息失败')
        } finally {
          this.loading = false
        }
      }
    },
    
    // 刷新设备信息
    async refreshDeviceInfo() {
      if (!this.currentDevice.id) return
      
      this.loading = true
      try {
        const deviceRes = await get('/device/findDeviceDetail', { id: this.currentDevice.id })
        this.currentDevice = deviceRes.data
        this.engineerInfo = this.currentDevice.engineer || {}
        this.$message.success('设备信息已刷新')
      } catch (error) {
        this.$message.error('刷新失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    // 切换地图显示状态
    toggleMap() {
      this.showMap = !this.showMap
    },
    
    // 时间格式化（支持时间戳和日期字符串）
    formatTime(timestamp) {
      if (!timestamp) return '-'
      
      // 处理时间戳（毫秒）
      if (typeof timestamp === 'number') {
        const date = new Date(timestamp)
        return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')} ${date.getHours().toString().padStart(2,'0')}:${date.getMinutes().toString().padStart(2,'0')}`
      }
      
      // 处理日期字符串
      return timestamp
    },
    
    // 地址格式化
    formatAddress(address) {
      if (!address) return '-'
      return address.replace('undefined', '').replace(/,+/g, ' ').trim() || '地址信息不完整'
    },
    
    // 状态标签类型
    getStatusType(status) {
      const statusMap = {
        '监测中': 'success',
        '已完工': 'info',
        '未开始': 'warning',
        '暂停': 'danger'
      }
      return statusMap[status] || 'info'
    },
    
    // 树节点过滤
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    
    // 获取工程设备树
    async getEmpData() {
      try {
        const res = await get('/dashboard/findEngineerDeviceTree')
        this.empData = res.data
      } catch (error) {
        this.$message.error('加载工程设备树失败')
      }
    }
  },
  created() {
    this.getEmpData()
  }
}
</script>

<style lang="scss" scoped>
.tree {
  height: calc(100vh - 60px);
  border-right: 1px solid #ededed;
  padding-right: 10px;
  margin-right: 10px;
}

.device-detail {
  padding: 20px;
  
  .box-card {
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 10px 20px rgba(0,0,0,0.05);
    }
  }
  
  .map-container {
    .map-placeholder {
      height: 400px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f7fa;
      color: #909399;
      border-radius: 4px;
    }
  }
}

.empty-tip {
  height: calc(100vh - 60px);
  display: flex;
  align-items: center;
  justify-content: center;
  
  .el-empty__image {
    margin-bottom: 20px;
  }
  
  .el-empty__description {
    margin-bottom: 15px;
  }
}

.mb-6 {
  margin-bottom: 1.5rem;
}
</style>